<?php
namespace app\controller\Admin;

use support\Request;
use support\Response;
use app\model\ScenicProduct;
use app\model\ProductPackageItem;
use app\model\ProductServiceTime;

class ScenicProductController
{
    /**
     * 获取产品列表
     * @param Request $request
     * @return Response
     */
    public function list(Request $request)
    {
        $query = ScenicProduct::query();
        
        // 查询条件
        if ($name = $request->input('name')) {
            $query->where('name', 'like', "%{$name}%");
        }
        if ($code = $request->input('code')) {
            $query->where('code', $code);
        }
        if ($type = $request->input('type')) {
            $query->where('type', $type);
        }
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        if ($categoryId = $request->input('category_id')) {
            $query->where('category_id', $categoryId);
        }
        if ($scenicSpotId = $request->input('scenic_spot_id')) {
            $query->where('scenic_spot_id', $scenicSpotId);
        }

        $data = $query->with(['category', 'scenicSpot'])
            ->orderBy('sort', 'desc')
            ->orderBy('product_id', 'desc')
            ->paginate($request->input('limit', 15));

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $data
        ]);
    }

    /**
     * 添加产品
     * @param Request $request
     * @return Response
     */
    public function add(Request $request)
    {
        $data = $request->post();
        
        // 开启事务
        \support\Db::beginTransaction();
        try {
            // 保存产品基本信息
            $product = new ScenicProduct();
            $product->fill($data);
            $product->save();

            // 如果是套餐，保存套餐明细
            if ($product->type === 'package' && !empty($data['package_items'])) {
                foreach ($data['package_items'] as $item) {
                    $packageItem = new ProductPackageItem();
                    $packageItem->product_id = $product->product_id;
                    $packageItem->fill($item);
                    $packageItem->save();
                }
            }

            // 保存服务时间
            if (!empty($data['service_times'])) {
                foreach ($data['service_times'] as $time) {
                    $serviceTime = new ProductServiceTime();
                    $serviceTime->product_id = $product->product_id;
                    $serviceTime->fill($time);
                    $serviceTime->save();
                }
            }

            \support\Db::commit();
            return json(['code' => 0, 'msg' => '添加成功']);
        } catch (\Exception $e) {
            \support\Db::rollBack();
            return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }

    /**
     * 编辑产品
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request)
    {
        $data = $request->post();
        $product = ScenicProduct::find($data['product_id']);
        if (!$product) {
            return json(['code' => 1, 'msg' => '产品不存在']);
        }

        // 开启事务
        \support\Db::beginTransaction();
        try {
            // 更新产品基本信息
            $product->fill($data);
            $product->save();

            // 更新套餐明细
            if ($product->type === 'package') {
                // 删除原有明细
                ProductPackageItem::where('product_id', $product->product_id)->delete();
                // 添加新明细
                if (!empty($data['package_items'])) {
                    foreach ($data['package_items'] as $item) {
                        $packageItem = new ProductPackageItem();
                        $packageItem->product_id = $product->product_id;
                        $packageItem->fill($item);
                        $packageItem->save();
                    }
                }
            }

            // 更新服务时间
            if (!empty($data['service_times'])) {
                // 删除原有时间
                ProductServiceTime::where('product_id', $product->product_id)->delete();
                // 添加新时间
                foreach ($data['service_times'] as $time) {
                    $serviceTime = new ProductServiceTime();
                    $serviceTime->product_id = $product->product_id;
                    $serviceTime->fill($time);
                    $serviceTime->save();
                }
            }

            \support\Db::commit();
            return json(['code' => 0, 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            \support\Db::rollBack();
            return json(['code' => 1, 'msg' => '编辑失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除产品
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request)
    {
        $productId = $request->input('product_id');
        $product = ScenicProduct::find($productId);
        if (!$product) {
            return json(['code' => 1, 'msg' => '产品不存在']);
        }

        // 开启事务
        \support\Db::beginTransaction();
        try {
            // 删除套餐明细
            ProductPackageItem::where('product_id', $productId)->delete();
            // 删除服务时间
            ProductServiceTime::where('product_id', $productId)->delete();
            // 删除产品
            $product->delete();

            \support\Db::commit();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            \support\Db::rollBack();
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 修改产品状态
     * @param Request $request
     * @return Response
     */
    public function changeStatus(Request $request)
    {
        $productId = $request->input('product_id');
        $status = $request->input('status');
        
        $product = ScenicProduct::find($productId);
        if (!$product) {
            return json(['code' => 1, 'msg' => '产品不存在']);
        }

        $product->status = $status;
        if ($product->save()) {
            return json(['code' => 0, 'msg' => '状态修改成功']);
        }
        return json(['code' => 1, 'msg' => '状态修改失败']);
    }
} 